package com.yoshino.singleton.type5;

import lombok.extern.slf4j.Slf4j;

/**
 * @author yoshino
 **/
@Slf4j
public class SingletonTest05 {
    public static void main(String[] args) {
        // 测试
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        // true
        log.info(String.valueOf(instance == instance2));
        log.info(instance.hashCode() + "");
        log.info(instance2.hashCode() + "");
    }
}

// 懒汉式（线程安全，同步代码块）

@Slf4j
class Singleton {

    // 1.构造器私有化，外部不能 new

    private Singleton() {
    }
    // 2.本类内部创建对象实例

    private static Singleton instance;


    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                instance = new Singleton();
                log.info("第一次创建" + instance.hashCode());
            }
        }
        return instance;
    }



}